<?php
class MgMenusController extends AppController {

	var $name = 'MgMenus';
	var $helpers = array('Html', 'Form','Javascript');

	function index() {
		$this->MgMenu->recursive = 0;
		$this->set('mgMenus', $this->paginate());
	}

	function menuExt() {
		Configure::write('debug','0');
		$this->layout = 'ajax';
		$menuprincipal = $this->MgMenu->find('all',
		array ('fields'=>array('`MgMenu`.`id` as `no_id`','`MgMenu`.`padre` as `no_padre`','`MgMenu`.`titulo` as `text`','`MgMenu`.`dom_id` as `id`'),
											'conditions'=>array ('padre'=>'0',
																 'dom_id <>'=>'\'\''),
											'order'=>array('MgMenu.orden ASC')));
		$menuArray = array();
		$menu = array();
		$childrenArray= array();
		$childrenPrincipal = array();
		$children = array();
		foreach ($menuprincipal as $k => $v)
		{
			foreach ( $v as $k1 => $v1)
			{
				foreach ($v1 as $k2 =>$v2)
				{
					if (substr($k2,0,3) <> 'no_')
					{
						$menuArray[$k2] = "'".$v2."'";
					}
				}
				$count =  $this->MgMenu->find('count',
				array ('conditions'=>array ('padre'=>$v1['no_id'],
																 'dom_id <>'=>'""')));
				if ($count >0) {
					$childrenprincipal = $this->MgMenu->find('all',
					array ('fields'=>array('`MgMenu`.`titulo` as `text`','`MgMenu`.`dom_id` as `id`'),
											'conditions'=>array ('padre'=>$v1['no_id'],
																 'dom_id <>'=>'\'\''),
											'order'=>array('MgMenu.orden ASC')));

					foreach ($childrenprincipal as $kc => $vc){
						foreach($vc as $kc1 => $vc1)
						{
							foreach ($vc1 as $kc2 =>$vc2){
								$childrenArray[$kc2]= "'".$vc2."'";
							}
							$childrenArray['leaf'] = "'true'";
						}
						$childrenPrincipal[] = $childrenArray;
					}
					$menuArray['children'] = $childrenPrincipal;
					unset($childrenPrincipal);
				}
				else{
					$childrenArray['leaf'] = "'true'";
				}

				$menu[] = $menuArray;
			}
		}
		$this->set('menuprincipal',$menu);
	}
}
?>